<!-- @format -->

<template>
	<el-dialog :visible.sync="visible" :close-on-click-modal="false" :title="this.edit ? $tt('label_edit_box') + ` [${form.boxNo}]` : $tt('label_add_box')" custom-class="dialog_auto">
		<el-form label-width="auto" label-position="right" ref="Form" :model="form" :rules="rules">
			<el-row>
				<el-col :span="24">
					<el-form-item :label="$tt('label_box_code')" prop="boxNo">
						<!-- <span class="bold">{{ warehouseName }} / {{ warehouseCode }}</span> -->
						<div style="display: flex;">
							<ex_super_input v-model="form.boxNo" />
							<el-button style="margin-left: 15px;" type="text" @click="generateBoxNo">{{ $tt('label_generate_box_code') }}</el-button>
						</div>
						<div class="color_danger text_small bold">{{ $tt('tip_add_box_create_box_tip') }}</div>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row v-if="isPallet">
				<el-col :span="24">
					<el-form-item :label="$tt('label_pallet_code')" prop="palletNo">
						<ex_super_input v-model="form.palletNo" />
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="24">
					<el-form-item :label="$tt('label_select_sku')">
						<sku_selec_input class="w_fill" @changeItem="changeSku" :customerId="customerId" :multiple="false" />
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="24">
					<el-form-item :label="$tt('label_dimension_weight')" class="normal-row" :required="true">
						<el-row :gutter="24">
							<el-col :md="5" :sm="24">
								<el-form-item prop="boxLength">
									<ex_super_input v-model="form.boxLength" :prepend="$tt('label_length')" append="cm" @input="$refs.Form.validateField(['boxLength', 'boxWidth', 'boxHeight'])" />
								</el-form-item>
							</el-col>
							<el-col :md="5" :sm="24">
								<el-form-item prop="boxWidth">
									<ex_super_input v-model="form.boxWidth" :prepend="$tt('label_width')" append="cm" @input="$refs.Form.validateField(['boxLength', 'boxWidth', 'boxHeight'])" />
								</el-form-item>
							</el-col>
							<el-col :md="5" :sm="24">
								<el-form-item prop="boxHeight">
									<ex_super_input v-model="form.boxHeight" :prepend="$tt('label_height')" append="cm" @input="$refs.Form.validateField(['boxLength', 'boxWidth', 'boxHeight'])" />
								</el-form-item>
							</el-col>
							<el-col :md="5" :sm="24">
								<el-form-item prop="boxWeight">
									<ex_super_input v-model="form.boxWeight" :prepend="$tt('label_weight')" append="kg" />
								</el-form-item>
							</el-col>
						</el-row>
						<div class="color_danger text_small bold">{{ $tt('tip_create_box_size') }}</div>
					</el-form-item>
				</el-col>
			</el-row>

			<el-row>
				<el-col :span="24">
					<el-form-item label-width="0" prop="sku_list">
						<ex_super_table ref="SkuTable" :data="form.sku_list" :model="tableModel" :height="400" @selection-change="(e) => (selection = e)"> </ex_super_table>
						<div class="color_danger text_small bold">{{ $tt('tip_create_box_declared_value_and_insured_amount') }}</div>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>

		<span slot="footer" class="dialog_footer">
			<el-button @click="visible = false">{{ $tt('label_cancel') }}</el-button>
			<el-button type="primary" @click="submitBefore">{{ $tt('label_submit') }}</el-button>
		</span>
	</el-dialog>
</template>

<script>
const default_obj = {
	boxNo: '',
	palletNo: '',
	boxLength: '', //	bigdecimal 	箱子长度
	boxWidth: '', //	bigdecimal 	箱子宽度
	boxHeight: '', //	bigdecimal 	箱子高度
	boxWeight: '', //箱子重量
	sku_list: [],
};
import sku_selec_input from '@/component/sku_selec_input';
export default {
	components: { sku_selec_input },
	data() {
		return {
			oriBoxNo: null,
			form: _.cloneDeep(default_obj),
			isPallet: false,
			isInsured: false,

			edit: false,
			visible: false,
			TOB: false,
			customerId: null,
			customerName: null,
			customerCode: null,
			items: [],
			selection: [],
			requiredNumberRule: [
				{ required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
				{
					trigger: 'blur',
					validator: (r, v, cb) => {
						if (!this.$reg.PureNumber(v)) {
							return cb(this.$tt('tip_only_positive_pure_decimal'));
						} else if (Number(v <= 0)) {
							return cb(this.$tt('tip_no_less_equal_any', { type: '0' }));
						}
						cb();
					},
				},
			],

			rules: {
				boxNo: {
					required: true,
					trigger: 'blur',
					validator: (r, v, cb) => {
						if (_.isEmpty(v)) return cb(this.$tt('tip_can_no_empty'));
						if (this.items.some((it) => v == it.boxNo)) {
							return cb(this.$tt('tip_has_add_some_box_no'));
						}
						cb();
					},
				},
				palletNo: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },

				boxWeight: [
					{
						required: true,
						trigger: 'blur',
						label: 'label_weight',
						validator: (r, v, cb) => {
							if (!this.$ruleStandard({ v, cb, type: 'weight', required: true })) return;
							if (Number(this.form.boxWeight) < this.reduceSkuWeight()) {
								return cb(this.$tt('tip_item_no_less_any', { i18n: true, item: 'label_box_weight', type: 'label_sku_sum_weight' }));
							}
							cb();
						},
					},
				],
				boxLength: [
					{
						required: true,
						trigger: 'blur',
						label: 'label_length',
						validator: (r, v, cb) => {
							if (!this.$ruleStandard({ v, cb, type: 'dimen', required: true })) return;
							if (this.reduceBoxVolume() < this.reduceSkuVolume()) {
								return cb(this.$tt('tip_item_no_less_any', { i18n: true, item: 'label_box_volume', type: 'label_sku_sum_volume' }));
							}
							cb();
						},
					},
				],
				boxWidth: [
					{
						required: true,
						trigger: 'blur',
						label: 'label_width',
						validator: (r, v, cb) => {
							if (!this.$ruleStandard({ v, cb, type: 'dimen', required: true })) return;
							if (this.reduceBoxVolume() < this.reduceSkuVolume()) {
								return cb(this.$tt('tip_item_no_less_any', { i18n: true, item: 'label_box_volume', type: 'label_sku_sum_volume' }));
							}
							cb();
						},
					},
				],
				boxHeight: [
					{
						required: true,
						trigger: 'blur',
						label: 'label_height',
						validator: (r, v, cb) => {
							if (!this.$ruleStandard({ v, cb, type: 'dimen', required: true })) return;
							if (this.reduceBoxVolume() < this.reduceSkuVolume()) {
								return cb(this.$tt('tip_item_no_less_any', { i18n: true, item: 'label_box_volume', type: 'label_sku_sum_volume' }));
							}
							cb();
						},
					},
				],
				sku_list: [
					{
						required: true,
						trigger: 'blur',
						type: 'array',
						min: 1,
						message: this.$tt('tip_please_add_least_one_sku'),
					},
					{
						trigger: 'blur',
						type: 'array',
						validator: (r, v, cb) => {
							const skuGroup = _.groupBy(v, 'skuId');
							if (_.values(skuGroup).some((it) => it.length > 1)) {
								return cb(this.$t('tip_some_box_can_no_have_some_sku'));
							}
							cb();
						},
					},
				],
			},

			tableModel: [
				// { type: 'selection', clickToggle: true, },
				{ key: 'skuBarcode', label: 'label_sku_code', width: '140', 'show-overflow-tooltip': true },
				{ key: 'skuName', label: 'label_sku_info', width: '120', 'show-overflow-tooltip': true },
				{
					key: 'isElectrify',
					label: 'label_is_electrify',
					width: '120',
					'show-overflow-tooltip': true,
					formatter: (r, c, v, i) => this.$enumShow(v, 'YesOrNoEnum'),
				},
				{
					key: 'cartonSpec',
					label: 'label_carton_spec',
					if: () => this.TOB,
					formatter: (r, c, v) => (v ? `${v}/${this.$tt('label_box')}` : this.$t('data_temp_none')),
				},
				{
					key: 'quantity',
					label: 'label_inbound_count',
					'min-width': 120, //if: () => !this.TOB,
					render: (h, { column, row, index }) => {
						const value = row[column.property];
						return (
							<el-form-item prop={`sku_list.${index}.quantity`} rules={this.requiredNumberRule}>
								<el-input-number class='w_fill' value={value} onInput={(e) => this.$set(row, column.property, e)} step-strictly min={1} max={999999} />
							</el-form-item>
						);
					},
				},

				{
					key: 'skuDeclaredAmount',
					label: 'label_declared_value',
					width: 120,
					'show-overflow-tooltip': true,
					formatter: (r, c, v) => this.$formatNameCode(v, r.currencyCode),
				},
				{
					key: 'insuredAmount',
					label: 'label_single_sku_insurance_amount',
					'min-width': 120,
					if: () => this.isInsured,
					render: (h, { column, row, index }) => {
						if (!this.isInsured) return;
						const rule = {
							trigger: 'blur',
							validator: (r, v, cb) => {
								if (this.isInsured) {
									if (!_.isEmpty(v)) {
										if (!this.$reg.DigitNumber(v, 2, 9)) {
											return cb(this.$tt('tip_check_decimal_digit_int', { digit: 2, int: 9 }));
										} else if (Number(v) > Number(row.skuDeclaredAmount)) {
											return cb(this.$tt('tip_insured_amount_no_more_declared_amount'));
										}
									}
								}
								cb();
							},
						};
						const value = row[column.property];
						return (
							<el-form-item prop={`sku_list.${index}.${column.property}`} rules={rule}>
								<ex_super_input class='w_fill' value={value} onInput={(e) => this.$set(row, column.property, e)} append={row.currencyCode} />
							</el-form-item>
						);
					},
				},
				{
					type: 'operate',
					width: 130,
					operate: [
						{
							label: 'label_remove',
							class: 'button_text_danger',
							click: (row, i) => this.form.sku_list.splice(i, 1),
						},
					],
				},
			],
		};
	},
	props: {},

	computed: {},
	methods: {
		reduceBoxVolume() {
			return this.$math_mul(this.form.boxLength, this.form.boxWidth, this.form.boxHeight);
		},
		reduceSkuWeight() {
			return _.reduce(
				this.form.sku_list,
				(sum, it) => {
					const weight = this.$math_mul(it.skuWeight, it.quantity);
					return this.$math_add(sum, weight);
				},
				0
			);
			// return this.$math_mul(this.form.boxLength,this.form.boxWidth,this.form.boxHeight)
		},
		reduceSkuVolume() {
			return _.reduce(
				this.form.sku_list,
				(sum, it) => {
					const volume = this.$math_mul(it.skuLength, it.skuWidth, it.skuHeight, it.quantity);
					return this.$math_add(sum, volume);
				},
				0
			);
			// return this.$math_mul(this.form.boxLength,this.form.boxWidth,this.form.boxHeight)
		},
		generateBoxNo() {
			this.generate_loading = true;
			this.$ajax({
				url: this.$url['oms/generateBoxNo'],
				method: 'post',
				loading: true,
				data: {
					customerCode: this.customerCode,
				},
				success: (res) => {
					// this.$message.success(this.$tt('tip_operate_success'))
					this.form.boxNo = res.data;
				},
				complete: () => {
					this.generate_loading = false;
				},
			});
		},

		changeSku(e) {
			if (!e) return;
			const item = _.find(this.form.sku_list, (it) => it.skuId == e.id);
			if (item) {
				// if (this.TOB) return
				item.quantity = item.quantity + 1;
				return;
			} else {
				if (this.TOB) {
					if (this.form.sku_list.length >= 1) return this.$message.warning(this.$tt('tip_create_box_tob_no_mix'));
					// if (!(e.cartonSpec > 0)) return this.$message.warning(this.$tt("tip_sku_cartonSpec_error_modity_sku_data"))
				}
				let sku = Object.assign(
					{
						skuId: e.id,
						quantity: this.TOB && e.cartonSpec ? e.cartonSpec : 1,
						skuDeclaredAmount: e.skuDeclaredValue,
						insuredAmount: this.isInsured ? e.skuDeclaredValue : 0,
					},
					e
				);
				delete sku.id;
				this.form.sku_list.push(sku);
			}
		},
		show({ items, boxNo, customerId, TOB, isPallet, isInsured, customerCode }) {
			this.visible = true;

			let box_form = _.cloneDeep(default_obj);

			this.TOB = TOB;
			this.edit = !!boxNo;
			this.oriBoxNo = boxNo;
			this.items = items.filter((it) => it.boxNo != boxNo);
			box_form.sku_list = items.filter((it) => it.boxNo == boxNo);
			let item = _.head(box_form.sku_list);
			if (item) {
				box_form.boxNo = item.boxNo;
				if (item.palletNo) box_form.palletNo = item.palletNo;
				box_form.boxLength = item.boxLength;
				box_form.boxWidth = item.boxWidth;
				box_form.boxHeight = item.boxHeight;
				box_form.boxWeight = item.boxWeight;
			}
			this.form = box_form;
			this.customerId = customerId;
			this.customerCode = customerCode;
			this.isPallet = isPallet;
			this.isInsured = isInsured;
		},
		hide() {
			this.visible = false;
		},

		submitBefore() {
			if (this.$clickFast()) return;
			this.$refs['Form'].validate((valid) => {
				if (valid) {
					this.submit();
				} else {
					this.$message.error(this.$tt('form_validate_error'));
					return false;
				}
			});
		},
		submit() {
			let { sku_list, ...other } = this.form;

			if (!this.isPallet) delete other.palletNo;
			this.$emit('submitSuccess', {
				oriCode: this.oriBoxNo,
				code: this.form.boxNo,
				list: sku_list.map((it) => {
					return {
						isInsurance: this.isInsured && it.insuredAmount ? 'Y' : 'N',
						...it,
						...other,
					};
				}),
			});
			this.visible = false;
		},
	},
};
</script>
